package com.iwe.crm.user.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.iwe.crm.base.exception.CrmEnum;
import com.iwe.crm.base.exception.CrmException;
import com.iwe.crm.base.util.DateUtil;
import com.iwe.crm.user.bean.User;
import com.iwe.crm.user.mapper.UserMapper;
import com.iwe.crm.user.service.UserService;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(User user) {
        String allowIp = user.getAllowIps();
        user.setLoginPwd(SecureUtil.md5(user.getLoginPwd()));
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("loginAct",user.getLoginAct())
                        .andEqualTo("loginPwd",user.getLoginPwd());
        List<User> users = userMapper.selectByExample(example);
        //用户名或密码是否正确
        if(users.size() == 0){
            throw new CrmException(CrmEnum.USER_LOGIN_LOGINUSER);
        }else{
            user = users.get(0);
        }
        //账号是否失效
       String expireTime = user.getExpireTime();
       String now = DateUtil.dateToString(new Date());
       if(now.compareTo(expireTime) > 0){
           throw new CrmException(CrmEnum.USER_LOGIN_EXPIRE);
       }
        //账号是否被锁定
        if("0".equals(user.getLockState())){
            throw new CrmException(CrmEnum.USER_LOGIN_LOCKED);
        }
        //是否是允许登录的ip
        if(!user.getAllowIps().contains(allowIp)){
            throw new CrmException(CrmEnum.USER_LOGIN_IP);
        }
        return user;
    }

    //异步校验输入的原始密码是否正确
    @Override
    public void verifyOldPwd(String oldPwd, User user) {
        String pwd = user.getLoginPwd();
        if(!SecureUtil.md5(oldPwd).equals(pwd)){
            throw new CrmException(CrmEnum.USER_UPDATE_OLDPWD);
        }
    }

    @Override
    public void updateUser(User user) {
        user.setLoginPwd(SecureUtil.md5(user.getLoginPwd()));
        int count = userMapper.updateByPrimaryKeySelective(user);

        if(count == 0){
            throw new CrmException(CrmEnum.USER_UPDATE_INFO);
        }
    }

    @Override
    public List<User> queryAllUsers() {
        return userMapper.selectAll();
    }
}
